﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Heartbeat.Core.Sensors
{
    public class CPUSensor : ISensor
    {
        private System.Diagnostics.PerformanceCounter cpuCounter;
        private SensorChannel _cpuInfo;        

        public CPUSensor(string machineName)
        {
            //todo: when the remote machine restarts (dies) the performancecounter class gets corrupts. I need a safe way to recreate it.
            //      I need to maintain an instance so NextValue() actually gives an average instead of '0' (always does this on first attempt).

            cpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", true);
            if (!string.IsNullOrEmpty(machineName))
            {
                cpuCounter.MachineName = machineName;
            }

            //var cat = new System.Diagnostics.PerformanceCounterCategory("Processor");
            //var counters = cat.GetInstanceNames();


            _cpuInfo = new SensorChannel() { Description = "CPU Load", Units = "%", DefaultLow = float.MinValue, DefaultHigh = 90.0f };         
        }

        public string Name
        {
            get { return "CPU"; }
        }
   
        public void Update()
        {
            _cpuInfo.Value = cpuCounter.NextValue();
        }

        public IEnumerable<ISensorChannel> Values
        {
            get 
            {
                yield return _cpuInfo;
            }
        }
    }
}
